/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Appearance.java
 *
 * Created on 19 Μαϊ 2011, 6:58:37 μμ
 */
package tools.options.panels;

import com.googlecode.svalidators.validators.ListValidator;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JColorChooser;
import javax.swing.JTextField;
import lap.LafAndPlay;
import myComponents.MyUsefulFunctions;
import myseriesproject.MySeries;
import myseriesproject.MySeriesConstants;
import tools.MySeriesLogger;
import tools.options.IMySeriesOptions;
import tools.options.MyOptionsFontRenderer;
import tools.options.MySeriesOptions;
import tools.options.Paths;

/**
 *
 * @author lordovol
 */
public class Appearance extends javax.swing.JPanel implements IMySeriesOptions {
  private static final long serialVersionUID = 1L;

  private DefaultComboBoxModel model_laf = new DefaultComboBoxModel();
  public boolean colorsChanged;
  public String oldFontSize;
  public String oldFontFace;
  public Color oldColor;
  public boolean oldUseSkin;
  public String oldLaf;
  private String[] fonts;
  private ComboBoxModel model_fonts;
  public LafAndPlay lap;

  /** Creates new form Appearance */
  public Appearance() {
    initComponents();
    combobox_laf.setEnabled(!checkbox_dontUseSkin.isSelected());
    oldFontFace = MySeries.options.getStringOption(FONT_FACE);
    oldFontSize = MySeries.options.getStringOption(FONT_SIZE);
    oldColor = MySeries.options.getColorOption(SKIN_COLOR);
    oldUseSkin = MySeries.options.getBooleanOption(USE_SKIN);
    oldLaf = MySeries.options.getStringOption(LOOK_AND_FEEL);
    createModelFonts();
    JTextField t = (JTextField) combobox_fonts.getEditor().getEditorComponent();
    t.setText(MySeries.options.getStringOption(FONT_FACE));
  }

  private void createLafModel() {
    lap = new LafAndPlay(Paths.LAFS_PATH);
    lap.addDefaultLookAndFeels();
    try {
      lap.addExternalLookAndFeels();
    } catch (IOException ex) {
      MySeriesLogger.logger.log(Level.SEVERE, "Could not get external lafs", ex);
    } catch (Exception ex) {
      MySeriesLogger.logger.log(Level.SEVERE, "Could not get external lafs", ex);
    }
    combobox_laf.setModel(lap.getComboBoxModel());
  }

  private void createModelFonts() {
    MySeriesLogger.logger.log(Level.INFO, "Creating fonts model");
    //System.out.println(System.currentTimeMillis());
    fonts = getCachedFonts();
    model_fonts = new DefaultComboBoxModel(fonts);
    combobox_fonts.setModel(model_fonts);
    model_fonts.setSelectedItem(MySeries.options.getStringOption(FONT_FACE));
    combobox_fonts.addValidator(new ListValidator("", fonts, false));
    MySeriesLogger.logger.log(Level.INFO, "Added {0} fonts", model_fonts.getSize());
    //System.out.println(System.currentTimeMillis());
  }

  private String[] getCachedFonts() {
    MySeriesLogger.logger.log(Level.INFO, "Checking for cached fonts model");
    File c = new File(MySeriesOptions._USER_DIR_ + "/f.obj");
    if (c.exists() && (System.currentTimeMillis() - c.lastModified()) / 3600000 / 24 < 15) {
      MySeriesLogger.logger.log(Level.INFO, "Cached model exists an it's new.Reading file");
      try {
        FileInputStream fin = new FileInputStream(c);
        ObjectInputStream ois = new ObjectInputStream(fin);
        String[] f = (String[]) ois.readObject();
        ois.close();
        return f;
      } catch (Exception ex) {
        MySeriesLogger.logger.log(Level.SEVERE, "Could not read the fonts model file", ex);
        return null;
      }
    } else {
      MySeriesLogger.logger.log(Level.INFO, "Cached file does not exist or it's old.Creating it");
      
      GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
      String[] f = env.getAvailableFontFamilyNames();
      
      FileOutputStream fout;
      try {
        fout = new FileOutputStream(MySeriesOptions._USER_DIR_ + "/f.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(f);
        oos.close();
      } catch (IOException ex) {
        MySeriesLogger.logger.log(Level.SEVERE, "Could not create fonts model file", ex);
        return null;
      }
      return f;
      
    }

  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jLabel5 = new javax.swing.JLabel();
    combobox_laf = new javax.swing.JComboBox();
    checkbox_dontUseSkin = new javax.swing.JCheckBox();
    button_BGColor = new javax.swing.JButton();
    combobox_fonts = new com.googlecode.svalidators.formcomponents.SComboBox();
    jLabel10 = new javax.swing.JLabel();
    spinner_fontSize = new javax.swing.JSpinner();
    jLabel16 = new javax.swing.JLabel();
    label_preview = new javax.swing.JLabel();
    cb_minimizeTray = new javax.swing.JCheckBox();
    cb_randomizeLaf = new javax.swing.JCheckBox();
    bt_downloadLafs = new myComponents.myGUI.buttons.MyButtonInternet();

    setName("Appearance"); // NOI18N
    setPreferredSize(new java.awt.Dimension(350, 229));

    jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    jLabel5.setText("Look And Feel :");
    jLabel5.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
    jLabel5.setName("noname"); // NOI18N

    combobox_laf.setModel(model_laf);
    combobox_laf.setSelectedItem(MySeries.options.getStringOption(LOOK_AND_FEEL));
    combobox_laf.setName(LOOK_AND_FEEL);
    combobox_laf.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        combobox_lafActionPerformed(evt);
      }
    });

    checkbox_dontUseSkin.setSelected(MySeries.options.getBooleanOption(USE_SKIN));
    checkbox_dontUseSkin.setText("Use Skin :");
    checkbox_dontUseSkin.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    checkbox_dontUseSkin.setMargin(new java.awt.Insets(0, 0, 0, 0));
    checkbox_dontUseSkin.setName(USE_SKIN);
    checkbox_dontUseSkin.setOpaque(false);
    checkbox_dontUseSkin.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        checkbox_dontUseSkinActionPerformed(evt);
      }
    });

    button_BGColor.setBackground(MySeries.options.getColorOption(SKIN_COLOR));
    button_BGColor.setText("Set Color");
    button_BGColor.setName(SKIN_COLOR);
    button_BGColor.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        button_BGColorActionPerformed(evt);
      }
    });

    combobox_fonts.setMinimumSize(new java.awt.Dimension(23, 20));
    combobox_fonts.setName(FONT_FACE);
    combobox_fonts.setRenderer(new MyOptionsFontRenderer());
    combobox_fonts.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        combobox_fontsActionPerformed(evt);
      }
    });

    jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    jLabel10.setText("Font : ");
    jLabel10.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
    jLabel10.setName("noname"); // NOI18N

    spinner_fontSize.setModel(new javax.swing.SpinnerNumberModel());
    spinner_fontSize.setName(FONT_SIZE);
    spinner_fontSize.setOpaque(false);
    spinner_fontSize.setValue((int)MySeries.options.getFloatOption(FONT_SIZE));
    spinner_fontSize.addChangeListener(new javax.swing.event.ChangeListener() {
      public void stateChanged(javax.swing.event.ChangeEvent evt) {
        spinner_fontSizeStateChanged(evt);
      }
    });

    jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    jLabel16.setText("Font preview :");
    jLabel16.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

    setFont(getSelectedFont());
    label_preview.setText(String.valueOf(combobox_fonts.getSelectedItem()));
    label_preview.setName("noname"); // NOI18N

    cb_minimizeTray.setSelected(MySeries.options.getBooleanOption(MINIMIZE_TO_TRAY));
    cb_minimizeTray.setText("Minimize to tray");
    cb_minimizeTray.setToolTipText("Minimize Application to tray");
    cb_minimizeTray.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    cb_minimizeTray.setMargin(new java.awt.Insets(0, 0, 0, 0));
    cb_minimizeTray.setName(MINIMIZE_TO_TRAY);
    cb_minimizeTray.setOpaque(false);

    cb_randomizeLaf.setSelected(MySeries.options.getBooleanOption(RANDOMIZE_LAF));
    cb_randomizeLaf.setText("Use a random LAF on startup");
    cb_randomizeLaf.setMargin(new java.awt.Insets(0, 0, 0, 0));
    cb_randomizeLaf.setName(RANDOMIZE_LAF);
    cb_randomizeLaf.setOpaque(false);

    bt_downloadLafs.setToolTipText("Download Look and Feels");
    bt_downloadLafs.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bt_downloadLafsActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(cb_minimizeTray, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel5)
              .addGroup(layout.createSequentialGroup()
                .addComponent(checkbox_dontUseSkin)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(button_BGColor)
                .addGap(125, 125, 125))
              .addGroup(layout.createSequentialGroup()
                .addComponent(combobox_fonts, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(spinner_fontSize, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(label_preview, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))
              .addGroup(layout.createSequentialGroup()
                .addComponent(combobox_laf, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_downloadLafs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)))
            .addGap(65, 65, 65))
          .addGroup(layout.createSequentialGroup()
            .addComponent(cb_randomizeLaf, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
            .addGap(67, 67, 67))
          .addGroup(layout.createSequentialGroup()
            .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
            .addGap(65, 65, 65))))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jLabel5)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
          .addComponent(combobox_laf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(bt_downloadLafs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(cb_randomizeLaf)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(button_BGColor)
          .addComponent(checkbox_dontUseSkin))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(combobox_fonts, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(spinner_fontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(7, 7, 7)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(label_preview, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(18, 18, 18)
        .addComponent(cb_minimizeTray)
        .addContainerGap(10, Short.MAX_VALUE))
    );

    createLafModel();
    combobox_laf.setSelectedItem(MySeries.options.getStringOption(LOOK_AND_FEEL));
  }// </editor-fold>//GEN-END:initComponents

    private void combobox_lafActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combobox_lafActionPerformed
      //LookAndFeelInfo laf = (LookAndFeelInfo) lafMap.get(combobox_laf.getSelectedItem());
      //LookAndFeels.setLookAndFeel(m,laf);
}//GEN-LAST:event_combobox_lafActionPerformed

    private void checkbox_dontUseSkinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkbox_dontUseSkinActionPerformed
      combobox_laf.setEnabled(!checkbox_dontUseSkin.isSelected());
      cb_randomizeLaf.setEnabled(!checkbox_dontUseSkin.isSelected());
}//GEN-LAST:event_checkbox_dontUseSkinActionPerformed

    private void button_BGColorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_BGColorActionPerformed
      MySeriesLogger.logger.log(Level.INFO, "howing color browser");
      JColorChooser c = new JColorChooser(MySeries.options.getColorOption(SKIN_COLOR));
      Color newColor = JColorChooser.showDialog(null, "Choose a background color", MySeries.options.getColorOption(SKIN_COLOR));
      if (newColor != null) {
        MySeriesLogger.logger.log(Level.INFO, "Selected color {0}", newColor);
        button_BGColor.setBackground(newColor);
        colorsChanged = true;
      }
}//GEN-LAST:event_button_BGColorActionPerformed

    private void combobox_fontsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combobox_fontsActionPerformed
      label_preview.setFont(getSelectedFont());
      label_preview.setText(String.valueOf(combobox_fonts.getSelectedItem()));
}//GEN-LAST:event_combobox_fontsActionPerformed

    private void spinner_fontSizeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinner_fontSizeStateChanged
      int size = Integer.parseInt(String.valueOf(spinner_fontSize.getValue()));
      Font newFont = new Font(combobox_fonts.getSelectedItem().toString(), Font.PLAIN, size);
      label_preview.setFont(newFont);
}//GEN-LAST:event_spinner_fontSizeStateChanged

    private void bt_downloadLafsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_downloadLafsActionPerformed
      MyUsefulFunctions.browse(MySeriesConstants.GOOGLE_CODE_DOWNLOAD_URL);
    }//GEN-LAST:event_bt_downloadLafsActionPerformed

  private Font getSelectedFont() {
    Font font = new Font((String) combobox_fonts.getSelectedItem(), Font.PLAIN, (int) Float.parseFloat(String.valueOf(spinner_fontSize.getValue())));
    return font;
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private myComponents.myGUI.buttons.MyButtonInternet bt_downloadLafs;
  public javax.swing.JButton button_BGColor;
  public javax.swing.JCheckBox cb_minimizeTray;
  public javax.swing.JCheckBox cb_randomizeLaf;
  public javax.swing.JCheckBox checkbox_dontUseSkin;
  public com.googlecode.svalidators.formcomponents.SComboBox combobox_fonts;
  public javax.swing.JComboBox combobox_laf;
  private javax.swing.JLabel jLabel10;
  private javax.swing.JLabel jLabel16;
  private javax.swing.JLabel jLabel5;
  public javax.swing.JLabel label_preview;
  public javax.swing.JSpinner spinner_fontSize;
  // End of variables declaration//GEN-END:variables
}
